package aorise.com.frame;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hjq.toast.ToastUtils;


import java.util.ArrayList;
import java.util.List;

import aorise.com.frame.base.ActivityActionBarClick;
import aorise.com.frame.base.ActivityManager;
import aorise.com.frame.base.BBBaseActivity;
import aorise.com.frame.common.LogT;
import aorise.com.frame.service.TimerService;
import aorise.com.frame.ui.main.ContactsFragment;
import aorise.com.frame.ui.main.HomeFragment;
import aorise.com.frame.ui.main.PersonalFragment;
import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BBBaseActivity implements RadioGroup.OnCheckedChangeListener, ActivityActionBarClick {
    // 时间间隔
    private static final long EXIT_INTERVAL = 2000L;
    @BindView(R.id.fragments_container)
    FrameLayout fragmentsContainer;
//    @BindView(R.id.group_home)
    private  static RadioButton groupHome;
    @BindView(R.id.group_contacts)
    RadioButton groupContacts;
    @BindView(R.id.group_my)
    RadioButton groupMy;
//    @BindView(R.id.)
    private  static  RadioGroup mainRadioGroup;
    public static int index = 0;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
//    @BindView(R.id.title_back)
//    ImageView titleBack;
    @BindView(R.id.tv_test)
    TextView tvTest;
    // 如果要监听双击事件则数组长度为2，如果要监听3次连续点击事件则数组长度为3...
    private long[] mHints = new long[2];
    private HomeFragment homeFragment;
    private ContactsFragment contactsFragment;
    private PersonalFragment personalFragment;
    private Fragment currentFragment;
    private List<Fragment> fragmentList = new ArrayList<>();
    private boolean showContacts = false;
    private static final String CURRENT_FRAGMENT_KEY = "currentFragment";
    private int mainid;
//    private static final String HOME_FRAGMENT_KEY = "homeFragment";
//    private static final String CONTACT_FRAGMENT_KEY = "contactFragment";
//    private static final String PERSONAL_FRAGMENT_KEY = "personalFragment";

    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE};
    List<String> mPermissionList = new ArrayList<>();

    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mainRadioGroup = findViewById(R.id.main_radio_group);
        groupHome = findViewById(R.id.group_home);

        //开启刷新token定时器
        Intent i = new Intent(this, TimerService.class);
        startService(i);
//        View actionBarView = findViewById(R.id.main_actionbar);
//        initActionBar(actionBarView, this);
        ButterKnife.bind(this);
//        homeFragment = new HomeFragment();
//        contactsFragment = new ContactsFragment();
//        personalFragment = new PersonalFragment();
        mainRadioGroup.setOnCheckedChangeListener(this);
        groupHome.setChecked(true);
        SharedPreferences edit = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        showContacts = edit.getBoolean("contacts_query",false);

//        BBBaseActivity.setColor(this,0x000000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String testStr = ((FsApplication) getApplication()).getTestStr();
        if (testStr!=null){
            tvTest.setText(testStr);
        }

        mainid = getIntent().getIntExtra("mainid", -1);//获取intent值,默认是-1
        if (mainid >= 0){
            setCurrentTab(mainid);
        }

    }

    @Override
    protected void initData() {
        if (Build.VERSION.SDK_INT > 23) {
            mPermissionList.clear();//清空没有通过的权限
            for (int i = 0; i < permissions.length; i++) {
                if (ActivityCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);//添加还未授予的权限
                }
            }

            //申请权限
            if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
                ActivityCompat.requestPermissions(this, permissions, 2040);
            } else {
                //说明权限都已经通过，可以做你想做的事情去
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 2040:
                // 电话权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {//文件写入权限

                }

        }
    }

    @Override
    protected void initEvent() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            // 将mHints数组内的所有元素左移一个位置
            System.arraycopy(mHints, 1, mHints, 0, mHints.length - 1);
            // 获得当前系统已经启动的时间
            mHints[mHints.length - 1] = SystemClock.uptimeMillis();
            if ((SystemClock.uptimeMillis() - mHints[0]) > EXIT_INTERVAL) {
                showToast(getString(R.string.aorise_label_double_exit));
            } else {
                finish();
                ActivityManager.getInstance().appExit(getApplicationContext());
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            /*获取保存的fragment  没有的话返回null*/
            LogT.d("" + savedInstanceState.toString());
            currentFragment = (Fragment) getSupportFragmentManager().getFragment(savedInstanceState, CURRENT_FRAGMENT_KEY);
            if (currentFragment instanceof HomeFragment) {
                LogT.d("current fragment is HomeFragment");
                homeFragment = (HomeFragment) currentFragment;
                contactsFragment = new ContactsFragment();
                personalFragment = new PersonalFragment();

                addToList(homeFragment);
                addToList(contactsFragment);
                addToList(personalFragment);
            }
            if (currentFragment instanceof ContactsFragment) {
                LogT.d("current fragment is ContactsListFragment");
                contactsFragment = (ContactsFragment) currentFragment;
                homeFragment = new HomeFragment();
                personalFragment = new PersonalFragment();

                addToList(homeFragment);
                addToList(contactsFragment);
                addToList(personalFragment);
            }
            if (currentFragment instanceof PersonalFragment) {
                LogT.d("current fragment is PersonalFragment");
                personalFragment = (PersonalFragment) currentFragment;
                homeFragment = new HomeFragment();
                contactsFragment = new ContactsFragment();

                addToList(homeFragment);
                addToList(contactsFragment);
                addToList(personalFragment);
            }

        } else {
           // initFragment();
        }

    }


    private void addToList(Fragment fragment) {
        if (fragment != null) {
            fragmentList.add(fragment);
        }
        LogT.i("fragmentList数量" + fragmentList.size());
    }


    /*添加fragment*/
    private void showFragment(Fragment fragment) {

        /*判断该fragment是否已经被添加过  如果没有被添加  则添加*/
        if (!fragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().add(R.id.fragments_container, fragment).commit();
            /*添加到 fragmentList*/
            fragmentList.add(fragment);
        }
        LogT.i("fragmentList数量：" + fragmentList.size());
        for (Fragment frag : fragmentList) {

            if (frag != fragment) {
                /*先隐藏其他fragment*/
                LogT.i("隐藏" + fragment);
                getSupportFragmentManager().beginTransaction().hide(frag).commit();
            }
        }
        currentFragment = fragment;
        LogT.d("Now fragment is " + fragment + " home hide ? " + homeFragment.isHidden());
        getSupportFragmentManager().beginTransaction().show(fragment).commit();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        LogT.i("MainActivity onSaveInstanceState");
        /*fragment不为空时 保存*/
        if (currentFragment != null) {
            getSupportFragmentManager().putFragment(outState, CURRENT_FRAGMENT_KEY, currentFragment);
        }

        super.onSaveInstanceState(outState);
    }

    // 主页跳转
    public void setCurrentTab(int i) {
        try {
            index = i;
            if (index ==0){  //首页
                if (homeFragment == null) {
                    LogT.i("homeFragment 为空  创建");
                    homeFragment = new HomeFragment();
                }
                showFragment(homeFragment);
                groupHome.setChecked(true);
            }


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.group_home:
//                getActionbarTitleView().setText(R.string.home);
                if (homeFragment == null) {
                    LogT.i("homeFragment 为空  创建");
                    homeFragment = new HomeFragment();
                }
                showFragment(homeFragment);
                break;
            case R.id.group_contacts:
//                getActionbarTitleView().setText(R.string.contact_title);
                if (contactsFragment == null) {
                    LogT.i("contactsFragment 为空  创建");
                    contactsFragment = new ContactsFragment();
                }
                if(!showContacts){
                    ToastUtils.show("权限不足!");
                }
                showFragment(contactsFragment);
                break;
            case R.id.group_my:
//                getActionbarTitleView().setText(R.string.personal_title);
                if (personalFragment == null) {
                    LogT.i("personalFragment 为空  创建");
                    personalFragment = new PersonalFragment();
                }
                showFragment(personalFragment);
                break;
        }
    }

    @Override
    public void onBackClick() {
    }

    @Override
    public void onMenuClick() {

    }


}
